import React, { useEffect, useState } from 'react';
import { Card, List } from 'antd';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
import axios from 'axios';

// 配置 dayjs 使用 UTC 和时区插件
dayjs.extend(utc);
dayjs.extend(timezone);

// 创建 axios 实例
const api = axios.create({
  baseURL: 'http://localhost:7001',  // 后端地址
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true
});

const handleSubmit = async (formData) => {
  console.log("formData:", formData)
  try {
    // 使用正确的路径 /data/save
    const response = await api.post('/data/save', formData);
    console.log('Data saved:', response.data);
    alert('Data saved successfully!');
  } catch (error) {
    console.error('Error saving data:', error);
    alert('Error saving data');
  }
};

const Receiver = ({ payload }) => {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    const updateAndLog = async () => {
      if (payload?.topic) {
        setMessages(messages => [...messages, payload]);
        try {
          const messageObj = JSON.parse(payload.message);
          const newFormData = {
            temp: messageObj.params.temp,
            humi: messageObj.params.humi,
            time: dayjs().format('YYYY-MM-DD HH:mm:ss')

          };
          
          // 直接使用 newFormData 而不是等待 setFormData
          await handleSubmit(newFormData);
        } catch (error) {
          console.error('Error processing message:', error);
        }
      }
    };
    updateAndLog();
  }, [payload]); // 只依赖 payload

  const renderListItem = (item) => (
    <List.Item>
      <List.Item.Meta
        title={item.topic}
        description={item.message}
      />
    </List.Item>
  );

  return (
    <Card title="Receiver">
      <List
        size="small"
        bordered
        dataSource={messages}
        renderItem={renderListItem}
      />
    </Card>
  );
};

export default Receiver; 